# coding=utf-8
import re

from django import http
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.mixins import LoginRequiredMixin
from itsdangerous import BadData
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

from boxuegu import settings
from users.models import UserProfile


def generic_verify_email_url(email):
    # 创建实例对象
    s = Serializer(secret_key=settings.SECRET_KEY, expires_in=3600)
    # 组织数据
    data = {
        'email': email
    }
    # 加密数据
    token = s.dumps(data)
    # 返回数据
    verify_url = settings.EMAIL_VERIFY_URL + token.decode()
    return verify_url


def check_veryfy_email_token(active_code):
    # 创建实例对象
    s = Serializer(secret_key=settings.SECRET_KEY, expires_in=3600)
    # 解密

    result = s.loads(active_code)

    # 返回数据
    return result


def get_user_by_username(username):
    try:
        if re.match(r'1[3-9]\d{9}', username):
            user = UserProfile.objects.get(mobile=username)

        else:
            user = UserProfile.objects.get(username=username)
    except UserProfile.DoesNotExist:
        return None
    return user


class UsernameMoble(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        user = get_user_by_username(username)
        if user is not None and user.check_password(password):
            return user
